/* 公共方法--xDialog弹出层方法 */
;(function(win,$){
    var index  = 0;
    //默认配置
    var config = {
        type: 0
        , shadeClose: false
        , anim: 'scale' //默认动画类型
        , btn:['知道了']
        ,timer:2000
    };
    var ready = {
        extend: function (obj) {
            var newobj = JSON.parse(JSON.stringify(config));
            for (var i in obj) {
                newobj[i] = obj[i];
            }
            return newobj;
        }

    }
    Dialog = function(options){
        this.config = $.extend({}, config, options);
        this.index = index;
        this.view();
    }

    Dialog.prototype.view = function(){
        var that = this, config = that.config;
        // 按钮
        if (config.type != 0){
            config.btn = "";
        }
        var button  = (function(){
            typeof config.btn === 'sring' && (config.btn = [config.btn]);
            var btns = (config.btn || []).length, btndom;
            if(btns === 0 || !config.btn){  
                return ''
            }
            btndom = '<a href="javascript:;" yes type="1">' + config.btn[0] +'</a>'
            if(btns === 2){
                btndom = btndom + '<a href="javascript:;" no  type="0">'+config.btn[1]+'</a>';
            }
            return '<div class="x-dialog__footer">'+btndom+'</div>'
        })();

        var html = 
            '<div class="x-dialog ' + (config.type == 0 ? "" : "x-dialog--msg") + '" id="dialog' + that.index + '" index="' + that.index + '">'+
            '   <div class="x-dialog__main">'+ 
            '       <div class="x-dialog__body">' + (config.type == 0 ? '<div>' + config.msg + '</div>':'<p>' + config.msg + '</p>'  ) + '</div>' + button + 
        '   </div>'+
        '</div>';
        $('body').append(html);
        this.action(config);
        that.index = index++;
    }

    Dialog.prototype.action = function (config){
        var that = this;

        //确认取消
        var btn = function(){
            var type = this.getAttribute('type');
            type == '0' ? (config.no && config.no()) : (config.yes && config.yes(that.index));
            xDialog.close(that.index);
        }
        if(config.btn){
            $('.x-dialog__footer a').bind('click',function(e){
               btn.call(this);
            });
        }

        if (config.shadeClose) {
            $('#dialog'+index).on('click',function(){
                xDialog.close(that.index);
            })
        }
        if (config.type == 1) {
            setTimeout(function(){
                xDialog.close(that.index);
            }, config.timer);
        }
    }
    win.xDialog = {
        close:function(index){
            var ibox = $('#dialog'+index);
            if (!ibox) return;
            ibox.remove();
        },
        show:function(options){
            var d = new Dialog(options || {});
            return d.index;
        }
    }

})(window,jQuery);